#include <iostream>
#include <string>
#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>

using namespace std;
typedef websocketpp::server<websocketpp::config::asio> wsserver_t;

void http_callback(wsserver_t* svr, websocketpp::connection_hdl hd1)
{
    // 返回一个hello world的页面
    wsserver_t::connection_ptr con = svr->get_con_from_hdl(hd1);
    cout << "body: " << con->get_request_body() << endl;
    websocketpp::http::parser::request req = con->get_request();
    cout << "method: " << req.get_method() << endl;
    cout << "uri: " << req.get_uri() << endl;

    string body = "<html><body><h1>hello world</h1></body></html>";
    con->set_body(body);
    con->append_header("Content-Type", "text/html");
    con->set_status(websocketpp::http::status_code::ok);
}
void wsopen_callback(wsserver_t* svr, websocketpp::connection_hdl hd1)
{
    cout << "websocket握手成功\n";
}
void wsclose_callback(wsserver_t* svr, websocketpp::connection_hdl hd1)
{
    cout << "websocket连接断开\n";
}
void wsmsg_callback(wsserver_t* svr, websocketpp::connection_hdl hd1, wsserver_t::message_ptr msg)
{
    wsserver_t::connection_ptr con = svr->get_con_from_hdl(hd1);
    cout << "wsmsg: " << msg->get_payload() << endl;
    string rsq = "client say: " + msg->get_payload();
    con->send(rsq, websocketpp::frame::opcode::text);
}

int main()
{
    // 创建服务器
    wsserver_t wssvr;
    // 设置日志级别，none什么日志都不打印
    wssvr.set_access_channels(websocketpp::log::alevel::none);
    // 初始化调度器
    wssvr.init_asio();
    wssvr.set_reuse_addr(true);
    // 设置回调函数
    wssvr.set_http_handler(bind(&http_callback, &wssvr, std::placeholders::_1));
    wssvr.set_open_handler(bind(&wsopen_callback, &wssvr, std::placeholders::_1));
    wssvr.set_close_handler(bind(&wsclose_callback, &wssvr, std::placeholders::_1));
    wssvr.set_message_handler(bind(&wsmsg_callback, &wssvr, std::placeholders::_1, std::placeholders::_2));
    // 监听接口
    wssvr.listen(8000);
    // 开始获取连接
    wssvr.start_accept();
    // 开始运行
    wssvr.run();
    cout << "运行结束" << endl;
}

